define(['jquery', 'bootstrap', 'backend', 'table', 'form', 'vue', 'cookie'], function ($, undefined, Backend, Table, Form, Vue) {
    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'customer.audit/index' + location.search,
                    add_url: 'customer.audit/add',
                    // edit_url: 'customer.audit/edit',
                    // del_url: 'customer.audit/del',
                    multi_url: 'customer.audit/multi',
                    import_url: 'customer.audit/import',
                    table: 'customer',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'package_id',
                sortName: 'package_id',
                fixedColumns: true,
                fixedRightNumber: 1,
                queryParams: (params) => {
                    var filter = JSON.parse(params.filter)
                    var op = JSON.parse(params.op)

                    // filter.status = 1
                    // op.status = '='

                    params.filter = JSON.stringify(filter)
                    params.op = JSON.stringify(op)

                    return params
                },
                columns: [
                    [
                        {checkbox: true},
                        {field: 'package_id', title: __('ID')},
                        {
                            field: 'admin_info.nickname',
                            title: '销售',
                            operate: false,
                            table: table,
                            class: 'autocontent',
                            formatter: Table.api.formatter.content
                        },
                        {
                            field: 'kuaiji_names',
                            title: '已分配会计',
                            operate: false,
                            table: table,
                            class: 'autocontent',
                            formatter: Table.api.formatter.content
                        },
                        {
                            field: 'waiqin_names',
                            title: '已分配外勤',
                            operate: false,
                            table: table,
                            class: 'autocontent',
                            formatter: Table.api.formatter.content
                        },
                        {
                            field: 'sales_commission',
                            title: '销售提成',
                            operate: false,
                            table: table,
                            class: 'autocontent',
                            formatter: Table.api.formatter.content
                        },
                        {
                            field: 'account_commission',
                            title: '会计提成',
                            operate: false,
                            table: table,
                            class: 'autocontent',
                            formatter: Table.api.formatter.content
                        },
                        {
                            field: 'outworker_commission',
                            title: '外勤提成',
                            operate: false,
                            table: table,
                            class: 'autocontent',
                            formatter: Table.api.formatter.content
                        },

                        {
                            field: 'customer',
                            title: __('客户信息'),
                            operate: false,
                            formatter: function (value, row, index) {
                                var str = ''
                                if (value) {
                                    if (value.customer_identity == 0) {
                                        str += '客户姓名：' + value.full_name + '<br>'
                                        str += '身份证号码：' + value.idnumber + '<br>'
                                    } else {
                                        str += '公司名称：' + value.corporate_name + '<br>'
                                    }
                                }
                                return str
                            }
                        },
                        {
                            field: 'status',
                            title: '审核状态',
                            formatter: Table.api.formatter.status,
                            custom: {1: "orange", 2: "green", 3: "red"},
                            searchList: {0: '未提交', 1: '审核中', 2: '审核通过', 3: '审核不通过'}
                        },
                        {
                            field: 'service_list',
                            title: '包含服务',
                            operate: false,
                            formatter: function (value, row, index) {
                                var str = ''
                                value.forEach((item) => {
                                    str += item.service_name + '(<span style="color: #9a1a1a">￥</span>' + item.deal_price + ')<br/>'
                                })
                                return str
                            }
                        },


                        // {
                        //     field: 'signature_url',
                        //     title: __('Signature_url'),
                        //     operate: 'LIKE',
                        //     formatter: Table.api.formatter.url
                        // },
                        {
                            field: 'signature_time',
                            title: __('签名时间'),
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            autocomplete: false,
                            formatter: Table.api.formatter.datetime
                        },
                        {
                            field: 'create_time',
                            title: __('Create_time'),
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            autocomplete: false,
                            formatter: Table.api.formatter.datetime
                        },
                        {
                            field: 'operate',
                            title: __('Operate'),
                            table: table,
                            buttons: [
                                {
                                    name: 'addtabs',
                                    text: __('查看电子合同'),
                                    title: __('查看电子合同'),
                                    classname: 'btn btn-xs btn-success btn-addtabs',
                                    url: 'customer/package/previewContract',
                                },
                                {
                                    name: 'addtabs',
                                    text: __('编辑销售'),
                                    title: __('编辑销售'),
                                    classname: 'btn btn-xs btn-success btn-dialog',
                                    url: 'customer/audit/editSale',
                                },
                                {
                                    name: 'addtabs',
                                    text: __('会计信息'),
                                    title: __('查看会计'),
                                    classname: 'btn btn-xs btn-success btn-dialog',
                                    url: 'customer/package.user/index/identity/0',
                                },
                                {
                                    name: 'addtabs',
                                    text: __('外勤信息'),
                                    title: __('查看外勤'),
                                    classname: 'btn btn-xs btn-success btn-dialog',
                                    url: 'customer/package.user/index/identity/1',
                                },
                                {
                                    name: 'addtabs',
                                    text: __('查看详情'),
                                    title: __('查看详情'),
                                    extend: 'data-area=\'["80%","80%"]\'',
                                    classname: 'btn btn-xs btn-success btn-dialog',
                                    url: 'customer/audit/details',
                                },
                                {
                                    name: 'addtabs',
                                    text: __('审核通过'),
                                    title: __('审核通过'),
                                    url: 'customer/audit/saveStatus/status/2',
                                    classname: 'btn btn-xs btn-success btn-magic btn-ajax',
                                    success: function (data, ret) {
                                        table.bootstrapTable('refresh');
                                    },
                                    error: function (data, ret) {
                                        console.log(data, ret);
                                        Layer.alert(ret.msg);
                                        return false;
                                    },
                                    visible: function (row) {
                                        if (row.status == 1) {
                                            return true
                                        } else {
                                            return false
                                        }
                                    },
                                },
                                {
                                    name: 'addtabs',
                                    text: __('审核不通过'),
                                    title: __('审核不通过'),
                                    url: 'customer/audit/saveStatus/status/3',
                                    classname: 'btn btn-xs btn-danger btn-magic btn-ajax',
                                    success: function (data, ret) {
                                        table.bootstrapTable('refresh');
                                    },
                                    error: function (data, ret) {
                                        console.log(data, ret);
                                        Layer.alert(ret.msg);
                                        return false;
                                    },
                                    visible: function (row) {
                                        if (row.status == 1) {
                                            return true
                                        } else {
                                            return false
                                        }
                                    },
                                },

                            ],
                            events: Table.api.events.operate,
                            // formatter: Table.api.formatter.operate
                            formatter: function (value, row, index) {
                                var that = $.extend({}, this);
                                var table = $(that.table).clone(true);
                                if (row.status == 0 || row.status == 3) {
                                    // return true
                                } else {
                                    $(table).data("operate-edit", null);
                                }
                                //隐藏编辑按钮

                                that.table = table;
                                return Table.api.formatter.operate.call(that, value, row, index);
                            }
                        }
                    ]
                ],
                onLoadSuccess: function () {
                    var cookiefilenames = 'customer_index_controller';  //对应控制器列表页
                    table.on('column-switch.bs.table', function (e, json) {
                        var hideColumns = [];
                        $.each(table.bootstrapTable('getHiddenColumns'), function (i, item) {
                            hideColumns.push(item.field);
                        });
                        $.cookie('texie_' + cookiefilenames, JSON.stringify(hideColumns), {expires: 365, path: '/'});
                    });
                    if ($.cookie('texie_' + cookiefilenames)) {
                        $.each(JSON.parse($.cookie('texie_' + cookiefilenames)), function (i, item) {
                            table.bootstrapTable('hideColumn', item);
                        });
                    }
                }
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
            // Table.api.fixedheader(table);
        },
        add: function () {
            $.validator.config({
                rules: {
                    endtime: function (element) {
                        const start_time = $('input[name="row[start_time]"]').val()
                        if (!start_time) {
                            return '开始日期不能为空';
                        }
                        if (element.value < start_time) {
                            return '截止日期不能小于开始日期';
                        }
                    }
                }
            });


            const service = Config['service'] || []
            const types = [
                'gth',
                'xgmnsr',
                'ybnsr',
            ]
            $('#c-service').change((e) => {
                rendService()
            })
            $('input[name="row[corporate_type]"]').change(() => {
                rendService()
            })

            function rendService() {
                const value = $('#c-service').val()
                const corporate_type = $('input[name="row[corporate_type]"]:checked').val()

                var index = 0
                const field_name = 'serviceTable'

                var str = '<div style="margin-top: 10px;border: 1px solid #e8e8e8;border-bottom:none">'

                str += "<div style='display: flex;justify-content: space-evenly;align-items: center;border-bottom: 1px solid #e8e8e8'>"
                str += '<div style="width: 100%;padding: 5px;font-weight: bold">服务名称</div>'
                str += '<div style="width: 100%;border-left: 1px solid #e8e8e8;padding: 5px;font-weight: bold">标准价格</div>'
                str += "</div>"

                service.forEach(item => {
                    if (value.includes(item.id.toString())) {
                        str += "<div style='display: flex;justify-content: space-evenly;align-items: center;border-bottom: 1px solid #e8e8e8'>"
                        // str += '<div style="width: 100%;padding: 5px;">' + item.service_name + ' (标准价格:￥' + item[types[corporate_type] + '_standard_price'] + ')</div>'
                        str += '<div style="width: 100%;padding: 5px;font-size: 12px">' + item.service_name + '</div>'
                        str += '<div style="width: 100%;border-left: 1px solid #e8e8e8;padding: 5px;font-size: 12px">￥' + item[types[corporate_type] + '_standard_price'] + '</div>'
                        // str += '<div style="width: 100%;border-left: 1px solid #e8e8e8;padding: 5px;"><input value="' + item[types[corporate_type] + '_standard_price'] + '" name="row[' + field_name + '][' + index + '][cjjg]" placeholder="请输入成交价格" data-rule="required;" class="form-control"  type="text"/></div>'
                        str += "</div>"

                        str += '<input name="row[' + field_name + '][' + index + '][service_id]" value="' + item.id + '" type="hidden"/>'
                        str += '<input name="row[' + field_name + '][' + index + '][ledger_expenses]" value="' + item.ledger_expenses + '" type="hidden"/>'
                        str += '<input name="row[' + field_name + '][' + index + '][service_name]" value="' + item.service_name + '" type="hidden"/>'
                        str += '<input name="row[' + field_name + '][' + index + '][standard_price]" value="' + item[types[corporate_type] + '_standard_price'] + '" type="hidden"/>'
                        str += '<input name="row[' + field_name + '][' + index + '][cost_price]" value="' + item[types[corporate_type] + '_cost_price'] + '" type="hidden"/>'
                        str += '<input name="row[' + field_name + '][' + index + '][corporate_type]" value="' + corporate_type + '" type="hidden"/>'
                        index++
                    }
                })
                str += "</div>"
                $('#select-privew').html(str)
            }

            Controller.api.bindevent();
        },
        edit: function () {
            $.validator.config({
                rules: {
                    endtime: function (element) {
                        const start_time = $('input[name="row[start_time]"]').val()
                        if (!start_time) {
                            return '开始日期不能为空';
                        }
                        if (element.value < start_time) {
                            return '截止日期不能小于开始日期';
                        }
                    }
                }
            });

            const service = Config['service'] || []
            const types = [
                'gth',
                'xgmnsr',
                'ybnsr',
            ]
            $('#c-service').change((e) => {
                rendService()
            })
            $('input[name="row[corporate_type]"]').change(() => {
                rendService()
            })

            function rendService() {
                const value = $('#c-service').val()
                const corporate_type = $('input[name="row[corporate_type]"]:checked').val()

                var index = 0
                const field_name = 'serviceTable'

                var str = '<div style="margin-top: 10px;border: 1px solid #e8e8e8;border-bottom:none">'

                str += "<div style='display: flex;justify-content: space-evenly;align-items: center;border-bottom: 1px solid #e8e8e8'>"
                str += '<div style="width: 100%;padding: 5px;font-weight: bold">服务名称</div>'
                str += '<div style="width: 100%;border-left: 1px solid #e8e8e8;padding: 5px;font-weight: bold">标准价格</div>'
                str += "</div>"

                service.forEach(item => {
                    if (value.includes(item.id.toString())) {
                        str += "<div style='display: flex;justify-content: space-evenly;align-items: center;border-bottom: 1px solid #e8e8e8'>"
                        // str += '<div style="width: 100%;padding: 5px;">' + item.service_name + ' (标准价格:￥' + item[types[corporate_type] + '_standard_price'] + ')</div>'
                        str += '<div style="width: 100%;padding: 5px;font-size: 12px">' + item.service_name + '</div>'
                        str += '<div style="width: 100%;border-left: 1px solid #e8e8e8;padding: 5px;font-size: 12px">￥' + item[types[corporate_type] + '_standard_price'] + '</div>'
                        // str += '<div style="width: 100%;border-left: 1px solid #e8e8e8;padding: 5px;"><input value="' + item[types[corporate_type] + '_standard_price'] + '" name="row[' + field_name + '][' + index + '][cjjg]" placeholder="请输入成交价格" data-rule="required;" class="form-control"  type="text"/></div>'
                        str += "</div>"

                        str += '<input name="row[' + field_name + '][' + index + '][service_id]" value="' + item.id + '" type="hidden"/>'
                        str += '<input name="row[' + field_name + '][' + index + '][ledger_expenses]" value="' + item.ledger_expenses + '" type="hidden"/>'
                        str += '<input name="row[' + field_name + '][' + index + '][service_name]" value="' + item.service_name + '" type="hidden"/>'
                        str += '<input name="row[' + field_name + '][' + index + '][standard_price]" value="' + item[types[corporate_type] + '_standard_price'] + '" type="hidden"/>'
                        str += '<input name="row[' + field_name + '][' + index + '][cost_price]" value="' + item[types[corporate_type] + '_cost_price'] + '" type="hidden"/>'
                        str += '<input name="row[' + field_name + '][' + index + '][corporate_type]" value="' + corporate_type + '" type="hidden"/>'
                        index++
                    }
                })
                str += "</div>"
                $('#select-privew').html(str)
            }

            Controller.api.bindevent();
        },
        editsale: function () {
            Controller.api.bindevent();
        },
        details: function () {
            $('.edit_service_commission').click(function () {
                const field = $(this).attr('field')
                const id = $(this).attr('csid')
                const value = $(this).attr('value')
                layer.open({
                    type: 1,
                    area: ["350px", "200px"],
                    btn: ["确定", "取消"],
                    title: '修改提成',
                    skin: 'layui-layer-prompt',
                    content: "<input value='" + value + "' id=\"c-commission\" data-rule=\"required\" class=\"form-control\" name=\"row[commission]\" type=\"text\" >",
                    yes: function (index, layero) {
                        var commission = $(layero).find("#c-commission").val();
                        console.log(id, field, commission)
                        Backend.api.ajax({
                            url: "customer/service/saveCommission",
                            data: {id, field, commission}
                        }, function (res) {
                            console.log(res)
                            // $(".btn-refresh").trigger("click");
                            // Layer.close(index);
                            window.location.reload()
                        });
                    },
                    success: function () {
                        // Form.api.bindevent($("#reset-task-div"));
                    }
                });
            })

            $('#edit_account').click(function () {
                const package_id = $(this).attr('package_id')
                var value = $(this).attr('value')
                if (value) {
                    value = value.split(",")
                }
                const account = Config['account']
                var str = '<div id="account_select"><select id="c-account_select" class="form-control selectpicker" data-live-search="true" multiple="" name="row[service_ids][]">'
                account.forEach((item) => {
                    if (value.includes(item.id.toString())) {
                        str += '<option selected value="' + item.id + '">' + item.nickname + '</option>'
                    } else {
                        str += '<option value="' + item.id + '">' + item.nickname + '</option>'
                    }
                })
                str += '</select></div>'
                layer.open({
                    type: 1,
                    area: ["350px", "500px"],
                    btn: ["确定", "取消"],
                    title: '编辑会记信息',
                    skin: 'layui-layer-prompt',
                    content: str,
                    yes: function (index, layero) {
                        var val = $(layero).find("#c-account_select").val();
                        Backend.api.ajax({
                            url: "customer/audit/saveAccount",
                            data: {package_id, account_ids: val.join(',')}
                        }, function (res) {
                            window.location.reload()
                        });
                    },
                    success: function () {
                        Form.api.bindevent($("#account_select"));
                    }
                });

            })
            $('#edit_outworker').click(function () {
                const package_id = $(this).attr('package_id')
                var value = $(this).attr('value')
                if (value) {
                    value = value.split(",")
                }
                const account = Config['outworker']
                var str = '<div id="outworker_select"><select id="c-outworker_select" class="form-control selectpicker" data-live-search="true" multiple=""">'
                account.forEach((item) => {
                    if (value.includes(item.id.toString())) {
                        str += '<option selected value="' + item.id + '">' + item.nickname + '</option>'
                    } else {
                        str += '<option value="' + item.id + '">' + item.nickname + '</option>'
                    }
                })
                str += '</select></div>'
                layer.open({
                    type: 1,
                    area: ["350px", "500px"],
                    btn: ["确定", "取消"],
                    title: '编辑外勤信息',
                    skin: 'layui-layer-prompt',
                    content: str,
                    yes: function (index, layero) {
                        var val = $(layero).find("#c-outworker_select").val();
                        Backend.api.ajax({
                            url: "customer/audit/saveOutworker",
                            data: {package_id, outworker_ids: val.join(',')}
                        }, function (res) {
                            window.location.reload()
                        });
                    },
                    success: function () {
                        Form.api.bindevent($("#outworker_select"));
                    }
                });

            })
            Controller.api.bindevent();
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            }
        }
    };
    return Controller;
});
